package com.explorer.ider.bootguide.utils;

import android.annotation.SuppressLint;
import android.app.Service;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.util.Log;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.URL;
import java.net.URLConnection;
import java.util.Enumeration;

public class NetUtil {
	private static final String TAG ="NetUtil" ;
	static boolean DEBUG = true;
	public static String CONNECTIVITY_CHANGE = "android.net.conn.CONNECTIVITY_CHANGE";
	public static String RSSI_CHANGE = "android.net.wifi.RSSI_CHANGED";
	public static String WIFI_STATE_CHANGE = WifiManager.WIFI_STATE_CHANGED_ACTION;

	/**
	 *
	 * 
	 * @param context
	 * @return
	 */
	public static boolean isWifiConnect(Context context) {
		ConnectivityManager manager = (ConnectivityManager) context
				.getSystemService(Service.CONNECTIVITY_SERVICE);
		NetworkInfo wifiInfo = manager
				.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
		Log.d("zhaoyf","-----wifiINfo = "+wifiInfo);
		return wifiInfo.isConnected() && wifiInfo.isAvailable();
	}

	/**
	 * �ж�Ethernet�Ƿ����
	 */
	@SuppressLint("InlinedApi")
	public static boolean isEthernetConnect(Context context) {
		ConnectivityManager manager = (ConnectivityManager) context
				.getSystemService(Service.CONNECTIVITY_SERVICE);
		NetworkInfo etherInfo = manager
				.getNetworkInfo(ConnectivityManager.TYPE_ETHERNET);

		return etherInfo.isConnected() && etherInfo.isAvailable();
	}

	public static boolean isNetworkAvailable(Context context) {
		return isWifiConnect(context) || isEthernetConnect(context);
	}


	public static int wifiLevel(Context context) {
		WifiManager manager = (WifiManager) context
				.getSystemService(Service.WIFI_SERVICE);
		WifiInfo info = manager.getConnectionInfo();
		return Math.abs(info.getRssi());
	}


	public static InputStream getInputStream(String strUrl) {
		InputStream in = null;
		try {
			URL url = new URL(strUrl);
			URLConnection connection = url.openConnection();
			connection.setConnectTimeout(5000);
			connection.connect();
			in = connection.getInputStream();
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return in;
	}

	public static String getStringFromUrl(String strUrl) {
		Log.i(TAG, "getStringFromUrl: "+strUrl);
		InputStream in = null;
		String content = null;
		URL url;
		try {
			url = new URL(strUrl);
			URLConnection connection = url.openConnection();
			connection.setConnectTimeout(5000);
			connection.connect();
			in = connection.getInputStream();
			BufferedReader br = new BufferedReader(new InputStreamReader(in));
			String str = null;
			content = new String();
			while ((str = br.readLine()) != null) {
				content = content + str;
				str = null;
			}
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

		return content;
	}


	public static Bitmap downloadBitmap(String imageUrl) {
		Bitmap bitmap = null;
		HttpURLConnection conn = null;
		InputStream is = null;
		try {
			URL url = new URL(imageUrl);
			conn = (HttpURLConnection) url.openConnection();
			conn.setConnectTimeout(5 * 1000);
			conn.setReadTimeout(10 * 1000);
			is = conn.getInputStream();
			bitmap = BitmapFactory.decodeStream(is);
			if(DEBUG) Log.i("NetUtil", "����������ͼƬ");
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (conn != null) {
				conn.disconnect();
			}
			if (is != null) {
				try {
					is.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return bitmap;
	}

//	public static Bitmap loadBitmap(String url) {
//		String path = Constant.CACHE_PATH + File.separator
//				+ getNameFromUrl(url);
//		Bitmap bitmap = null;
//		File file = new File(Constant.CACHE_PATH + File.separator
//				+ getNameFromUrl(url));
//		try {
//			HttpURLConnection connection = (HttpURLConnection) (new URL(url)
//					.openConnection());
//
//			if (!file.exists()) {
//				if(DEBUG) Log.i("NetUtil", "��������ͼƬ" + url);
//				downloadImage2Disk(url);
//			} else {
//				if (file.length() != connection.getContentLength()) {
//
//					if(DEBUG) Log.i("NetUtil", "ɾ�����ش����ͼƬ");
//					file.delete();
//					downloadImage2Disk(url);
//				}
//			}
//			connection.getContentLength();
//		} catch (MalformedURLException e) {
//			e.printStackTrace();
//		} catch (IOException e) {
//			e.printStackTrace();
//		}
//		bitmap = BitmapFactory.decodeFile(path);
//		return bitmap;
//	}

	public static Bitmap createScaledBimtap(Bitmap bmp, int dstWidth,
			int dstHeight) {
		Bitmap dst = Bitmap.createScaledBitmap(bmp, dstWidth, dstHeight, false);
		if (bmp != dst) {
			bmp.recycle();
		}
		return dst;
	}


//	public static void downloadImage2Disk(String url) {
//		File file = new File(Constant.CACHE_PATH + File.separator
//				+ getNameFromUrl(url));
//		if (!file.exists()) {
//			HttpURLConnection conn = null;
//			FileOutputStream fos = null;
//			InputStream is = null;
//			try {
//				URL picUrl = new URL(url);
//				conn = (HttpURLConnection) picUrl.openConnection();
//				conn.setConnectTimeout(5 * 1000);
//				conn.setReadTimeout(10 * 1000);
//				is = conn.getInputStream();
//				fos = new FileOutputStream(file);
//				byte[] buffer = new byte[1024];
//				int length;
//				while ((length = is.read(buffer)) != -1) {
//					fos.write(buffer, 0, length);
//				}
//			} catch (FileNotFoundException e) {
//				e.printStackTrace();
//			} catch (IOException e) {
//				e.printStackTrace();
//			} finally {
//				if (is != null) {
//					try {
//						is.close(); // �ر�������
//					} catch (IOException e) {
//						e.printStackTrace();
//					}
//				}
//				if (fos != null) {
//					try {
//						fos.close(); // �ر��ļ������
//					} catch (IOException e) {
//						e.printStackTrace();
//					}
//				}
//			}
//
//		}
//	}

	public static String getNameFromUrl(String url) {
		String name = null;
		if(url == null) {
			return null;
		}
		int regionStart = url.lastIndexOf("/") + 1;
		int regionEnd = url.length() - 4;
		if(url.length() > 4 && regionStart != 0 && regionStart < regionEnd) {
			name = url.substring(regionStart, regionEnd);
			return name;
		}
		return null;
	}

//	private static final String APPLICATION_JSON = "application/json";
//
//	private static final String CONTENT_TYPE_TEXT_JSON = "text/json";
//
//	public static void httpPostWithJSON(String url, String json) {
//		// 将JSON进行UTF-8编码,以便传输中
//		try{
////        String encoderJson = URLEncoder.encode(json, HTTP.UTF_8);
//
//			DefaultHttpClient httpClient = new DefaultHttpClient();
//			HttpPost httpPost = new HttpPost(url);
//			httpPost.addHeader(HTTP.CONTENT_TYPE, APPLICATION_JSON);
//
//			StringEntity se = new StringEntity(json);
//			Log.i("MAC", json);
//			se.setContentType(CONTENT_TYPE_TEXT_JSON);
//			se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, APPLICATION_JSON));
//			httpPost.setEntity(se);
//			httpClient.execute(httpPost);
//		}
//		catch(Exception e){
//			e.printStackTrace();
//		}
//	}

	public static String getLocalEthernetMacAddress() {
		String mac=null;
		try {
			Enumeration localEnumeration=NetworkInterface.getNetworkInterfaces();

			while (localEnumeration.hasMoreElements()) {
				NetworkInterface localNetworkInterface=(NetworkInterface) localEnumeration.nextElement();
				String interfaceName=localNetworkInterface.getDisplayName();

				if (interfaceName==null) {
					continue;
				}

				if (interfaceName.equals("eth0")) {
					// MACAddr = convertMac(localNetworkInterface
					// .getHardwareAddress());
					mac=convertToMac(localNetworkInterface.getHardwareAddress());
					if (mac!=null&&mac.startsWith("0:")) {
						mac="0"+mac;
					}
					break;
				}
			}
		} catch (SocketException e) {
			e.printStackTrace();
		}
		return mac;
	}

	private static String convertToMac(byte[] mac) {
		StringBuilder sb=new StringBuilder();
		for (int i=0; i<mac.length; i++) {
			byte b=mac[i];
			int value=0;
			if (b>=0&&b<=16) {
				value=b;
				sb.append("0"+Integer.toHexString(value));
			} else if (b>16) {
				value=b;
				sb.append(Integer.toHexString(value));
			} else {
				value=256+b;
				sb.append(Integer.toHexString(value));
			}
			if (i!=mac.length-1) {
				sb.append(":");
			}
		}
		return sb.toString();
	}
}
